
var isPhone = (window.navigator.platform != "Win32");
var isAndroid = (window.navigator.userAgent.indexOf('Android') > -1)?true : false;
var isIPhone = (window.navigator.userAgent.indexOf('iPhone') > -1)?true:false;
var  isIPhonex =( window.screen.height == 812 && window.screen.width == 375 && window.devicePixelRatio === 3)?true:false;
var page_dom_ready = function(callback) {
    if (document.readyState === "complete" || document.readyState === "loaded" || document.readyState === "interactive") {
        callback();
    } else {
        document.addEventListener("DOMContentLoaded", callback, false);
    }
}
var bankLogos = {
        "005":{"logoSrc": "js_bank","bankName": "建设银行"},
        "002":{"logoSrc": "gs_bank","bankName": "工商银行(直接支付)"},
        "004":{"logoSrc": "zg_bank","bankName": "中国银行"},
        "003":{"logoSrc": "ny_bank","bankName": "农业银行"},
        "934":{"logoSrc": "yc_bank","bankName": "邮储银行"},
        "016":{"logoSrc": "gf_bank","bankName": "广发银行"},
        "012":{"logoSrc": "hx_bank","bankName": "华夏银行"},
        "006":{"logoSrc": "jt_bank","bankName": "交通银行"},
        "007":{"logoSrc": "zs_bank","bankName": "招商银行"},
        "014":{"logoSrc": "ms_bank","bankName": "民生银行"},
        "010":{"logoSrc": "pf_bank","bankName": "浦发银行"},
        "011":{"logoSrc": "xy_bank","bankName": "兴业银行"},
        "015":{"logoSrc": "zx_bank","bankName": "中信银行"},
        "920":{"logoSrc": "pa_bank","bankName": "平安银行"},
        "009":{"logoSrc": "gd_bank","bankName": "光大银行"},
        "922":{"logoSrc": "bj_bank","bankName": "北京银行"},
        "xxx":{"logoSrc": "bank_logo"},
        "superxjb":{"logoSrc": "pay-arrow"},
        "online":{"logoSrc": "pay-arrow"},
        "offline":{"logoSrc": "payway-offline"},
        "xjb":{"logoSrc": "pay-arrow"},
        "0feilv":{"logoSrc": "plan-0feilv"},
        "salary":{"logoSrc": "plan-salary"},
        "period":{"logoSrc": "plan-period"},
        "nfxjb":{"logoSrc":"logo-nfxjb"},
        "arrow":{"logoSrc":"pay-arrow"},
        
        // 一键购图标设置
        "superxjb-payway":{"logoSrc": "pay-superxjb-payway"},
        "online-payway":{"logoSrc": "pay-online-payway"},
        "offline-payway":{"logoSrc": "pay-offline-payway"},
        "originalxjb-payway":{"logoSrc": "pay-originalxjb-payway"}
};


page_dom_ready(function() {//修正不同设备显示情况
    var baseFontSize = 10;
    var baseWidth = 320;
    //var dpr = window.devicePixelRatio;
    var innerWidth = Math.max(Math.min(window.innerWidth, 414), 320);
    var rem = Math.floor(innerWidth / baseWidth * baseFontSize) * 10;
    document.documentElement.style.fontSize = rem + 'px';
});

function hideAddressBar_ios() {
    if (document.documentElement.scrollHeight <= document.documentElement.clientHeight) {
        bodyTag = document.getElementsByTagName('body')[0];
        bodyTag.style.height = document.documentElement.clientWidth / screen.width * screen.height + 'px';
    }
    setTimeout(function() {
        window.scrollTo(0, 1);
    }, 100);
};
function hideAddressBar_android() {
    var n = navigator.userAgent;
    if (n.match(/UCBrowser/i)) {
        //uc浏览器
        hideAddressBar_ios();
        return false;
    }
    var self = document.getElementsByTagName('body')[0];
    if (self.requestFullscreen) {
        self.requestFullscreen();
    } else if (self.mozRequestFullScreen) {
        self.mozRequestFullScreen();
    } else if (self.webkitRequestFullScreen) {
        self.webkitRequestFullScreen();
    }
};
window.addEventListener("load", function() {
    //navigator.userAgent.match(/Android/i) ? hideAddressBar_android() : hideAddressBar_ios();
});

function Encrypt(word) {
    var AESkey = "nffund2015cs9903";
    var key = CryptoJS.enc.Utf8.parse(AESkey);
    //
    var iv = CryptoJS.enc.Utf8.parse(AESkey);
    var srcs = CryptoJS.enc.Utf8.parse(word.trim());
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv : iv,
        mode : CryptoJS.mode.CBC
    });
    return encrypted.toString();
}
function Decrypt(word){
    var crypt = JSON.parse(getLocVal("crypt")); 
    try{
        if(crypt==2){           
            var AESkey = "nffund2015cs9903";
            var key = CryptoJS.enc.Utf8.parse(AESkey);
            var iv = CryptoJS.enc.Utf8.parse(AESkey);
            var decrypted = CryptoJS.AES.decrypt(word, key, {
                iv : iv,
                mode : CryptoJS.mode.CBC
            });
            return CryptoJS.enc.Utf8.stringify(decrypted).toString(); 
        } 
    }catch(e){
    }
    return word;
}
function weixinControl() {
    var useragent = navigator.userAgent;
    if(iswechat()==false){
        // 这里警告框会阻塞当前页面继续加载
        // 以下代码是用javascript强行关闭当前页面
        var opened = window.open('about:blank', '_self');
        opened.opener = null;
        opened.close();
    }
}

function setLocVal(namespace,value){
    if(namespace.indexOf('.')>-1){
        var _arr = namespace.split('.');
        var copy= context = {};
        var _len = _arr.length;
        for (var i = 0; i<_len; i++) {
            var str = _arr[i];
            if(i==0&&window.localStorage[_arr[0]]){
                context[str] = JSON.parse(window.localStorage[_arr[0]]);   
            }
            if (!context[str]){
                context[str] = {};
            }
            if(i==_len-1){
                context[str] = value;
            }else{
                context = context[str];//递归
            }
        };
        window.localStorage[_arr[0]] = JSON.stringify(copy[_arr[0]]);
    } else{
        window.localStorage[namespace] = value;
    }
}

/**
 * 获取缓存
 * @param Striong namespace  保存数据的keys，如果不传清空所有缓存数据
 * namespace格式：使用'.'作为命名空间分隔符或者默认格式
 */    
function getLocVal(namespace){
    var _arr = namespace.split('.');
    var _len = _arr.length;
    var data = window.localStorage[_arr[0]];
    if(_len==1){
       return data||"";
    }
    if(!data) {
        return ""
    }else{
        data = JSON.parse(data);
    }
    for (var i = 1; i <_len; i++) {
        data = data[_arr[i]];
        if(!data){
            return ""
        }
    };
    if(typeof(data)=='string'){//保证返回的都是字符串
            return data;
    }else{
        return JSON.stringify(data);
    }
}

/**
 * 清除缓存
 * @param Striong keys  保存数据的keys，如果不传清空所有缓存数据
 * keys格式：多个key可以用',' 分隔，每个key的可以使用'.'作为命名空间分隔符
 */
// function clearLocVal(keys){
    // if(keys){
        // var keyArr = keys.split(',');//用逗号分隔多个键值
        // for (var i=0; i < keyArr.length; i++) {
            // localStorage.removeItem(keyArr[i]);
        // }
    // }else{
        // localStorage.clear();
    // }
// }
function clearLocVal(keys){
    if(keys){
        var keyArr = keys.split(',');//用逗号分隔多个键值
        for (var i=0; i < keyArr.length; i++) {
            if(keyArr[i].indexOf('.')>-1){
                var _arr = keyArr[i].split('.');
                var _len = _arr.length;
                var data = getLocVal(_arr[0]);
                if(!data) {
                    return ;
                }else{
                    data = JSON.parse(data);
                }   
                for (var j = 1; j <_len; j++) {
                    data = data[_arr[j]];
                    if(!data){
                        return;
                    }
                };
                if(data){
                    setLocVal(keyArr[i],'');
                }
              }else{
                window.localStorage.removeItem(keyArr[i]);
              }  
        };
    }else{
        window.localStorage.clear();
    }
}

function getRiskName(id) {
    var risklevelname = "低";
    switch (id) {
    case '1':
    case 1:
        risklevelname = "低";
        break;
    case '2':
    case 2:
        risklevelname = "中低";
        break;
    case '3':
    case 3:
        risklevelname = "中";
        break;
    case '4':
    case 4:
        risklevelname = "中高";
        break;
    case '5':
    case 5:
        risklevelname = "高";
        break;
    }
    return risklevelname;
}

//用户风险等级转换
function getRiskAbility(id) {
    var riskAbilityName = "";
    switch (id) {
    case '1':
        riskAbilityName = "安全型";
        break;
    case '2':
        riskAbilityName = "保守型";
        break;
    case '3':
        riskAbilityName = "稳健型";
        break;
    case '4':
        riskAbilityName = "积极型";
        break;
    case '5':
        riskAbilityName = "进取型";
        break;
    }
    return riskAbilityName;
}

var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
function generateRandom(n) {
    var res = "";
    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
}

function format(num) {
    if (num.indexOf(',') > -1) {
        num = num.replace(/,/g, '');
    }
    if (num.indexOf('.') > -1) {
        if (num.substr(num.indexOf('.'), num.length).length > 2) {
            num = parseFloat(num).toFixed(2);
        }
    }
    num = num+"";
    return num.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}

function json2str(obj) {
    return JSON.stringify(obj);
}

function fl2(fl) {
    fl += '';
    if (fl.indexOf('.') == -1) {
        return fl + ".00";
    } else {
        var arr = fl.split('.');
        if (arr[1].length < 2) {
            arr[1] += '0';
        } else {
            arr[1] = arr[1].slice(0, 2);
        }
        return arr.join('.');
    }
}
function fl3(fl){
    fl+='';
    if(fl.indexOf('.')==-1){
        return fl+".000";
    }else{
        var arr=fl.split('.');
        if(arr[1].length<3){
            arr[1]+='000';
        }
        arr[1]=arr[1].slice(0,3);
        return arr.join('.');
    }       
}

function fl4(fl) {
    fl += '';
    if (fl.indexOf('.') == -1) {
        return fl + ".0000";
    } else {
        var arr = fl.split('.');
        if (arr[1].length < 4) {
            arr[1] += '0000';
        }
        arr[1] = arr[1].slice(0, 4);
        return arr.join('.');
    }
}

function toDate(date) {
    if (date.length == 8) {
        var dateStr = "";
        dateStr += date.substr(0, 4) + "-";
        dateStr += date.substr(4, 2) + "-";
        dateStr += date.substr(6, 2);
        return dateStr;
    } else {
        return date;
    }
}

//分红方式转换
function getMelonStr(melonmethod) {
    var melonmethodStr = "";
    switch (melonmethod) {
    case '0':
        melonmethodStr = "红利再投资";
        break;
    case '1':
        melonmethodStr = "现金红利 ";

    }
    return melonmethodStr;
}

function isDefine(value) {
    if (value == null || value == "" || value == "undefined" || value == undefined || value == "null" || value == "(null)" || value == 'NULL' || typeof (value) == 'undefined') {
        return false;
    } else {
        value = value + "";
        value = value.replace(/\s/g, "");
        if (value == "") {
            return false;
        }
        return true;
    }
}

Date.prototype.format = function(format) {
    var o = {
        "M+" : this.getMonth() + 1, //month
        "d+" : this.getDate(), //day
        "h+" : this.getHours(), //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth() + 3) / 3), //quarter
        "S" : this.getMilliseconds() //millisecond
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        //$1、$2、...、$99与 regexp 中的第 1 到第 99 个子表达式相匹配的文本
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            //o[k]长度可能为 1 2: 1显示"0"+o[k]，2直接显示o[k]
        }
    }
    return format;
}
function login() {
    if (islogin()==false){      
        judgeJumpReloginUrl("login.html");
    }
}

function historyBack(comefrom) {
    if(browser.versions.safari){
          sessionStorage.setItem('historyBack',"1");  
    }
    if(comefrom=='login'){
        location.href = "index.html";
    }else{
        window.history.back();
       //window.history.go(-1);window.location.reload();
    }
}

function checkSessionkey() {
    if (islogin()==false) {
        judgeJumpReloginUrl("login.html");
        return false;
    }
    return true;
}

var isShowTopBtn = (function() {//单例
    //var isShow = false;
    return function() {
        var min_height = 300;
        //if (isShow || (document.body.scrollTop < min_height)) {//scrollTop<min_height不创建
        //     return;
        //}
        //$('body').append('<div class="top-btn"></div>')
        //isShow = true;
        function b() {
            if (document.body.scrollTop > min_height) {
                $(".top-btn").addClass('top-btn-fadein');
            } else {
                $(".top-btn").removeClass('top-btn-fadein')
            }
        }


        $('.top-btn').on('click', function(e) {
            e.preventDefault();
            window.scrollTo(0, 0)
        }), b(), window.addEventListener("scroll", b);
    }
})();

function PageJumps(relPath, param) {
    var joinParam = '',
        i = 0;
    for (var key in param) {
        joinParam += ((i++ > 0) ? '&' : '?') + key + '=' + parm[key];
    }
    window.location.href = relPath + joinParam;
}

function paramSerialize(obj,paramKey) {
    var i = 0;
    var arr = [];
    for (var key in obj) {
        if (key !== 'keys'&& key!= paramKey) {//排除keys键
            arr[i++] = key + '=' + obj[key];
        }
    }
    return arr.join('&');
}

function paramQuery() {
    var params = {};
    var loc = document.location + '';
    if (loc.indexOf("?") > 0) {
        loc = loc.substr(loc.indexOf('?') + 1);
    } else {
        return {};
    }

    var pieces = loc.split('&');
    params.keys = [];
    for (var i = 0; i < pieces.length; i += 1) {
        var keyVal = pieces[i].split('=');
        params[keyVal[0]] = decodeURIComponent(keyVal[1]);
        params.keys.push(keyVal[0]);
    }
    return params;
}

function getHashParams(t) {//获取哈希参数
    var e = t ? t : decodeURIComponent(location.hash),
        i = [],
        n = {};
    return e.replace(/[\.\?'"><:;,\[\]\{\}]/gi, ""),
    i = e.split("/"), i.length > 0 && (n.__vpageid = i.splice(0, 1)[0].substring(1), n.urlParams = i.length > 0 ? parseUrl(i.join("/"), !0) : {}), n
}

function parseUrl(t, e) {
    var i,
        n,
        a,
        o = t.split("&"),
        r = {};
    for ( a = o.length,
    i = 0; a > i; i++)
        o[i].indexOf("=") < 0 ? r[o[i]] =
        void 0 : ( n = o[i].split("="), r[n[0]] = e ? decodeURIComponent(n[1]) : n[1]);
    return r
};

window.ZENG = window.ZENG || {};

ZENG.dom = {
    getById : function(id) {
        return document.getElementById(id);
    },
    get : function(e) {
        return ( typeof (e) == "string") ? document.getElementById(e) : e;
    },
    createElementIn : function(tagName, elem, insertFirst, attrs) {
        var _e = ( elem = ZENG.dom.get(elem) || document.body).ownerDocument.createElement(tagName || "div"),
            k;
        if ( typeof (attrs) == 'object') {
            for (k in attrs) {
                if (k == "class") {
                    _e.className = attrs[k];
                } else if (k == "style") {
                    _e.style.cssText = attrs[k];
                } else {
                    _e[k] = attrs[k];
                }
            }
        }
        insertFirst ? elem.insertBefore(_e, elem.firstChild) : elem.appendChild(_e);
        return _e;
    },
    getStyle : function(el, property) {
        el = ZENG.dom.get(el);
        if (!el || el.nodeType == 9) {
            return null;
        }
        var w3cMode = document.defaultView && document.defaultView.getComputedStyle,
            computed = !w3cMode ? null : document.defaultView.getComputedStyle(el, ''),
            value = "";
        switch (property) {
        case "float":
            property = w3cMode ? "cssFloat" : "styleFloat";
            break;
        case "opacity":
            if (!w3cMode) {
                var val = 100;
                try {
                    val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity;
                } catch (e) {
                    try {
                        val = el.filters('alpha').opacity;
                    } catch (e) {
                    }
                }
                return val / 100;
            } else {
                return parseFloat((computed || el.style)[property]);
            }
            break;
        case "backgroundPositionX":
            if (w3cMode) {
                property = "backgroundPosition";
                return ((computed || el.style)[property]).split(" ")[0];
            }
            break;
        case "backgroundPositionY":
            if (w3cMode) {
                property = "backgroundPosition";
                return ((computed || el.style)[property]).split(" ")[1];
            }
            break;
        }
        if (w3cMode) {
            return (computed || el.style)[property];
        } else {
            return (el.currentStyle[property] || el.style[property]);
        }
    },
    setStyle : function(el, properties, value) {
        if (!( el = ZENG.dom.get(el)) || el.nodeType != 1) {
            return false;
        }
        var tmp,
            bRtn = true,
            w3cMode = ( tmp = document.defaultView) && tmp.getComputedStyle,
            rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i;
        if ( typeof (properties) == 'string') {
            tmp = properties;
            properties = {};
            properties[tmp] = value;
        }
        for (var prop in properties) {
            value = properties[prop];
            if (prop == 'float') {
                prop = w3cMode ? "cssFloat" : "styleFloat";
            } else if (prop == 'opacity') {
                if (!w3cMode) {
                    prop = 'filter';
                    value = value >= 1 ? '' : ('alpha(opacity=' + Math.round(value * 100) + ')');
                }
            } else if (prop == 'backgroundPositionX' || prop == 'backgroundPositionY') {
                tmp = prop.slice(-1) == 'X' ? 'Y' : 'X';
                if (w3cMode) {
                    var v = ZENG.dom.getStyle(el, "backgroundPosition" + tmp);
                    prop = 'backgroundPosition';
                    typeof (value) == 'number' && ( value = value + 'px');
                    value = tmp == 'Y' ? (value + " " + (v || "top")) : ((v || 'left') + " " + value);
                }
            }
            if ( typeof el.style[prop] != "undefined") {
                el.style[prop] = value + ( typeof value === "number" && !rexclude.test(prop) ? 'px' : '');
                bRtn = bRtn && true;
            } else {
                bRtn = bRtn && false;
            }
        }
        return bRtn;
    },
    getScrollTop : function(doc) {
        var _doc = doc || document;
        return Math.max(_doc.documentElement.scrollTop, _doc.body.scrollTop);
    },
    getClientHeight : function(doc) {
        var _doc = doc || document;
        return _doc.compatMode == "CSS1Compat" ? _doc.documentElement.clientHeight : _doc.body.clientHeight;
    }
};

ZENG.string = {
    RegExps : {
        trim : /^\s+|\s+$/g,
        ltrim : /^\s+/,
        rtrim : /\s+$/,
        nl2br : /\n/g,
        s2nb : /[\x20]{2}/g,
        URIencode : /[\x09\x0A\x0D\x20\x21-\x29\x2B\x2C\x2F\x3A-\x3F\x5B-\x5E\x60\x7B-\x7E]/g,
        escHTML : {
            re_amp : /&/g,
            re_lt : /</g,
            re_gt : />/g,
            re_apos : /\x27/g,
            re_quot : /\x22/g
        },
        escString : {
            bsls : /\\/g,
            sls : /\//g,
            nl : /\n/g,
            rt : /\r/g,
            tab : /\t/g
        },
        restXHTML : {
            re_amp : /&amp;/g,
            re_lt : /&lt;/g,
            re_gt : /&gt;/g,
            re_apos : /&(?:apos|#0?39);/g,
            re_quot : /&quot;/g
        },
        write : /\{(\d{1,2})(?:\:([xodQqb]))?\}/g,
        isURL : /^(?:ht|f)tp(?:s)?\:\/\/(?:[\w\-\.]+)\.\w+/i,
        cut : /[\x00-\xFF]/,
        getRealLen : {
            r0 : /[^\x00-\xFF]/g,
            r1 : /[\x00-\xFF]/g
        },
        format : /\{([\d\w\.]+)\}/g
    },
    commonReplace : function(s, p, r) {
        return s.replace(p, r);
    },
    format : function(str) {
        var args = Array.prototype.slice.call(arguments),
            v;
        str = String(args.shift());
        if (args.length == 1 && typeof (args[0]) == 'object') {
            args = args[0];
        }
        ZENG.string.RegExps.format.lastIndex = 0;
        return str.replace(ZENG.string.RegExps.format, function(m, n) {
            v = ZENG.object.route(args, n);
            return v === undefined ? m : v;
        });
    }
};

ZENG.object = {
    routeRE : /([\d\w_]+)/g,
    route : function(obj, path) {
        obj = obj || {};
        path = String(path);
        var r = ZENG.object.routeRE,
            m;
        r.lastIndex = 0;
        while (( m = r.exec(path)) !== null) {
            obj = obj[m[0]];
            if (obj === undefined || obj === null) {
                break;
            }
        }
        return obj;
    }
};

var ua = ZENG.userAgent = {},
    agent = navigator.userAgent;
ua.ie = 9 - ((agent.indexOf('Trident/5.0') > -1) ? 0 : 1) - (window.XDomainRequest ? 0 : 1) - (window.XMLHttpRequest ? 0 : 1);

if ( typeof (ZENG.msgbox) == 'undefined') {
    ZENG.msgbox = {};
}
ZENG.msgbox._timer = null;
ZENG.msgbox.loadingAnimationPath = ZENG.msgbox.loadingAnimationPath || ("loading.gif");
ZENG.msgbox.show = function(msgHtml, type, timeout, opts) {
    if ( typeof (opts) == 'number') {
        opts = {
            topPosition : opts
        };
    }
    opts = opts || {};
    var _s = ZENG.msgbox,
        template = '<span class="zeng_msgbox_layer" style="display:none;z-index:10000;" id="mode_tips_v2"><span class=""></span>{loadIcon}{msgHtml}<span class="gtl_end"></span></span>',
        loading = '<span class="gtl_ico_loading"></span>',
        typeClass = [0, 0, 0, 0, "succ", "fail", "clear"],
        mBox,
        tips;
    _s._loadCss && _s._loadCss(opts.cssPath);
    mBox = ZENG.dom.get("q_Msgbox") || ZENG.dom.createElementIn("div", document.body, false, {
        className : "zeng_msgbox_layer_wrap"
    });
    mBox.id = "q_Msgbox";
    mBox.style.display = "";
    mBox.innerHTML = ZENG.string.format(template, {
        type : typeClass[type] || "hits",
        msgHtml : msgHtml || "",
        loadIcon : type == 6 ? loading : ""
    });
    _s._setPosition(mBox, timeout, opts.topPosition);
};
ZENG.msgbox._setPosition = function(tips, timeout, topPosition) {
    timeout = timeout || 5000;
    var _s = ZENG.msgbox,
        bt = ZENG.dom.getScrollTop(),
        ch = ZENG.dom.getClientHeight(),
        t = Math.floor(ch / 2) - 40;
    ZENG.dom.setStyle(tips, "top", ((document.compatMode == "BackCompat" || ZENG.userAgent.ie < 7) ? bt : 0) + (( typeof (topPosition) == "number") ? topPosition : t) + "px");
    clearTimeout(_s._timer);
    tips.firstChild.style.display = "";
    timeout && (_s._timer = setTimeout(_s.hide, timeout));
};
ZENG.msgbox.hide = function(timeout) {
    var _s = ZENG.msgbox;
    if (timeout) {
        clearTimeout(_s._timer);
        _s._timer = setTimeout(_s._hide, timeout);
    } else {
        _s._hide();
    }
};
ZENG.msgbox._hide = function() {
    var _mBox = ZENG.dom.get("q_Msgbox"),
        _s = ZENG.msgbox;
    clearTimeout(_s._timer);
    if (_mBox) {
        var _tips = _mBox.firstChild;
        ZENG.dom.setStyle(_mBox, "display", "none");
    }
};

$toast = function(tip, time, i) {
    if (time) {
        ZENG.msgbox.show(tip, i, time);
    } else {
        ZENG.msgbox.show(tip, i, 3000);
    }
}
$closeToast = function(tip, time, i) {
    ZENG.msgbox.hide();
}
function toast(){
    nfApp.loading(true);
}

/**
 * 手动关闭加载框
 */
function closeToast(){
    nfApp.loading(false);
}
/*
 * parameter：type:'alert',//alert/confirm
 hasTitle:false,
 title:'温馨提示',
 content:'',
 button:{
 cancel:'忽&nbsp略',
 confirm:'查&nbsp看'
 },
 cancelCallback:null,
 confirmCallback:null
 * */
function jqueryForm(postData,id) {
    require(['jqueryForm'], function(jqueryForm) {//dialog
        //dialog(options);
          jQuery("#"+id).ajaxForm(postData);
    });
}
function dialog(options) {
    require(['dialog'], function(dialog) {//dialog
        dialog(options);
    });
}

function paywaySel(options) {
    require(['m_selectPayway'], function(m_selectPayway) {//引入selectBox模块
        m_selectPayway.initialize(options);
    });
}

function selectBox(options) {
    require(['m_selectBox'], function(m_selectBox) {//引入selectBox模块
        m_selectBox.initialize(options);
    });
}
function selectDate(options) {
    require(['m_selectDate'], function(m_selectDate) {//引入selectBox模块
        m_selectDate.initialize(options);
    });
}

function dateActionSel(options) {
    require(['m_dateActionSel'], function(m_dateActionSel) {//dateActionSel
        m_dateActionSel.initialize(options);
    });
}
function actionSel(options){
    require(['m_actionSel'], function(m_actionSel) {//actionSel
        m_actionSel.initialize(options);
    });
}

function judgeRisk(confirmFun) {//判断是否做风险测评
    var riskexpired = localStorage.getItem('riskexpired');
    var riskability = localStorage.getItem('riskability');
    var   confirmCallback = '';
    if(confirmFun){
       confirmCallback =  confirmFun
    }else{
        confirmCallback  = function(){
                location.href = 'risk.html'
        }
    }
    if( getLocVal( "riskinfo") == 0){
            var riskTip = '您尚未进行风险承受能力测评，请先进行测评后再进行基金交易。';
        }else{
            var riskTip = '您的风险承受能力测评需要进行更新，请重新测评后再进行基金交易。'; 
        }
    
    if (riskexpired == 'true' ) {//过期，直接做风险测评
        dialog({
            type : 'confirm',
            hasTitle : false,
            content : riskTip,
            button : {
                cancel : '暂不测评',
                confirm : '立即测评'
            },
            cancelCallback : null,
            confirmCallback :confirmCallback
        });
        return false;
    } else {
        // if (riskability == '1') {//风险测评等级为1，可能刚开户未做风险测评，或者风险等级就为1，因此需要判断答案是否为空是否是新开户用户
            // getRiskResults(confirmFun);
            // //登录过后riskexpired==false&&riskability=='1'自动修正riskexpired==true值
        // } else {//无需提示     
             return true;
       // }
    }
}

//货币型基金判断是否购买
function canBuy(){//canBuy字段
    var riskexpired =getLocVal('riskexpired');//
    var riskability =getLocVal('riskability');//
    if(getLocVal('originalString') == 'DCVALID'||riskexpired=='true'){//过期，直接做风险测评
       // setLocVal("canBuy","false");
        if( getLocVal('investorType') != 1 ){//不是专业投资者
            setLocVal("canBuy","false");
        }else{//如果是专业投资者就都可以买
            setLocVal("canBuy",true);
        }
    }else{
        setLocVal("canBuy",true);
        // if(riskability=='1'){//风险测评等级为1，可能刚开户未做风险测评，或者风险等级就为1，因此需要判断答案是否为空是否是新开户用户
            // getRiskResults();
        // }else{
            // setLocVal("canBuy",riskability);
        // }
    }
}

if( !islogin() ){//如果未登录状态，清除canbuy标记
     setLocVal("canBuy","");
}else{
    if( getLocVal("canBuy") ){//如果登录状态下，canbuy标记没有设置，则调用方法进行设置
        canBuy();
    }
}

function showRiskMessage(confirmFun){
     var   confirmCallback = '';
    if(confirmFun){
       confirmCallback =  confirmFun
    }else{
        confirmCallback  = function(){
                location.href = 'risk.html'
        }
    }
    if( getLocVal( "riskinfo") == 0){
            var riskTip = '您尚未进行风险承受能力测评，请先进行测评后再进行基金交易。';
        }else{
            var riskTip = '您的风险承受能力测评需要进行更新，请重新测评后再进行基金交易。'; 
        }  
        
         dialog({
            type : 'confirm',
            hasTitle : false,
            content : riskTip,
            button : {
                cancel : '暂不测评',
                confirm : '立即测评'
            },
            cancelCallback : null,
            confirmCallback :confirmCallback
        });  
}

function getRiskResults(confirmFun) {
    var j = {
        "function" : "C004",
        "sessionkey" : localStorage.getItem("sessionkey"),
        "accoreqserial" : "",
    };
    nfApp._ajax(j, function(data) {
        if (data.code = SUCCESS_FLAG) {
            // if (!data.risklist[0].myanswer) {//答案为空，设置不能立刻购买
                // localStorage.setItem('riskexpired', 'true')//用该字段判断，是否做风险测评
                // judgeRisk(confirmFun);
            // }
            if(data.risklist[0].myanswer == "") {//答案为空，设置不能立刻购买
                setLocVal("canBuy","false");
            }else {
                setLocVal("canBuy",getLocVal('riskability'));
            }
        }
    });
}

function tradeError(data) {
    if (data.code == PWD_ERROR1||data.code == PWD_ERROR2) {
        var callback = function(){
                        location.href = 'findPwd_trade.html'
                };
                dialog({
                    type : 'confirm',
                    hasTitle : false,
                    content : data.message,
                    button : {
                         cancel : '<div class="ub-con" style="background-color: white;height: 3em;border-right: 1px solid #DFDFDF;">找回交易密码</div>',
                        confirm : '<div class="ub-con" style="background-color: white;height: 3em;">确&nbsp定</div>'
                    },
                    cancelCallback : callback,
                    confirmCallback :null
                });                  
            return;
    }else{
        dialog({
            type : 'alert',
            content:data.message
        });
        return;
    }
}

function checkAge(sn) {//判断是否已满18周岁
    if (!sn || sn.length < 15) {
        return false;
    }
    var bstr = '';
    if (sn.length == 18) {
        bstr = sn.substring(6, 14);
    } else if (sn.length == 15) {
        bstr = '19' + sn.substring(6, 12);
    }
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - bstr.substring(0, 4) - 1;
    if (bstr.substring(4, 6) < month || bstr.substring(4, 6) == month && bstr.substring(6, 8) <= day) {
        age++;
    }
    return age >= 18;
}
//flag:1首页 -1：现金宝页面 0:超时处理
function wechatlogin(callback,flag,pageNext,context) {
    if(window.localStorage.getItem('forgetlock')){
        location.href='login.html?h5lock=1';
    }               
    var j = {
        "function" : "WX001",
        "weixinid":sessionStorage.getItem("weixinid"),
        'interfaceversion':'2'
    };        
    nfApp._ajax(j, function(data) {
        if (data.code == SUCCESS_FLAG) {
            sessionStorage.removeItem("notbind");
            sessionStorage.setItem("weixinlogin","1");
            saveLogin(data);
            if(flag==2){//手势密码页面跳转前验证是否已绑定
                window.location.href = pageNext;
            }
            else if(callback&&flag!=-1){
                callback.call(context||null,pageNext);//回调
            }else if(callback&&flag==-1){
                callback();
            }
        }else if(data.code == 'WX-LG001'){
            sessionStorage.setItem("notbind","1");
            localStorage.removeItem('passwordxx');//未绑定时删除手势密码
            if(flag==2){//手势密码页面跳转前，如果未绑定，不跳转到手势密码页面
                return true;
            }
           if(flag==1&&callback){
               callback(pageNext);//回调
           }else if(flag==-1&&callback){
               callback(pageNext);
           } 
           localStorage.removeItem(localStorage.getItem("eqcustno")+'wealthIndex');
           judgeJumpReloginUrl("index.html");
        }else {
            $toast(data.message);
//          $toast('您还未开户或绑定账号，请先开户或绑定账号');
        }
    });
}

function saveLogin(json) {
    localStorage.setItem('sessionkey', json.sessionkey);
    sessionStorage.setItem('sessionkey',json.sessionkey);        
    localStorage.setItem('eqcustno', json.eqcustno);
    localStorage.setItem('custno', json.custno);
    sessionStorage.setItem('email', json.email);
    localStorage.setItem("riskUpdateTime", json.riskUpdateTime);
    localStorage.setItem("riskability", json.riskability);
    localStorage.setItem("idtype", json.idtype);
    localStorage.setItem("riskexpired", json.riskexpired);
    localStorage.setItem('originalString', json.originalString);
    localStorage.setItem('msgUploadCount', json.msgUploadCount);
    var curTime = new Date().getTime();
    localStorage.setItem('lastupdatetime', curTime+'');
    sessionStorage.setItem('handset', json.handset);
    sessionStorage.setItem("idno", Encrypt(json.idno));
    sessionStorage.setItem("customerappellation", Encrypt(json.customerappellation));
    /*---分割线------新增弱认证保存字段------*/
    sessionStorage.setItem("accountId", json.accountId);
    localStorage.setItem("custType", json.custType);//弱认证客户W，强认证客户S
    localStorage.setItem("level", json.level);//可用积分
    localStorage.setItem("active", json.active);
    localStorage.setItem("isFirstLogin", json.isFirstLogin);
    localStorage.setItem("openMobileLogin", json.openMobileLogin);
    localStorage.setItem("total", json.total);//积分数量
    localStorage.setItem("userRank", json.userRank);
    localStorage.setItem("scoreSign", json.scoreSign);//签名，积分商城使用
    localStorage.setItem("crypt", "2");//加密存储
    sessionStorage.setItem('loginflag', "1");
    
    localStorage.setItem("participationId",json.participationId);//是否有权限参加体验金
    localStorage.setItem("infoflag",json.infoflag);//infoflag==0时表示信息不完善
    sessionStorage.setItem("infoflag",json.infoflag);//infoflag==0时表示信息不完善
    localStorage.setItem("riskinfo",json.riskinfo);//0：表示客户没有做过风险测评，1:表示客户已做过风险测评，2:表示风险测评问卷有更新，客户需要重新做
    sessionStorage.setItem("riskinfo",json.riskinfo);//0：表示客户没有做过风险测评，1:表示客户已做过风险测评，2:表示风险测评问卷有更新，客户需要重新做
    localStorage.setItem("lowRiskLimit",json.lowRiskLimit);//1:表示风险等级为1的客户不能购买其他基金
    sessionStorage.setItem("lowRiskLimit",json.lowRiskLimit);//1:表示风险等级为1的客户不能购买其他基金
    localStorage.setItem("investorType",json.investorType);//1表示专业投资者，其他为普通投资者
    localStorage.setItem("moneyRiskLimit",json.moneyRiskLimit);//1：表示货币基金需要风险测评
    sessionStorage.setItem("moneyRiskLimit",json.moneyRiskLimit);//1：表示货币基金需要风险测评
    sessionStorage.setItem("zeroRiskFlag",json.zeroRiskFlag);//当风险等级为1时，区分C0和C1 0：表示C0 1：表示C1
    sessionStorage.setItem("newRisk",json.newRisk);//当风险等级为1时，区分C0和C1 0：表示C0 1：表示C1
    sessionStorage.setItem("maxRiskLevel",json.maxRiskLevel);//当风险等级为1时，区分C0和C1 0：表示C0 1：表示C1
     localStorage.setItem("idEndFlag",json.idEndFlag);
    
    try{
        if(_paq!=undefined){
            _paq.push(['setUserId', sessionStorage.getItem('accountId')]); 
        }
    }catch(e){}
    canBuy();
}
function islogin(){
    var curTime = new Date().getTime();//获取当前时间(从1970.1.1开始的毫秒数)
    if(sessionStorage.getItem("loginflag")=="1"){
        if(curTime-getLocVal("lastupdatetime")<600000){//10分钟
            if(sessionStorage.getItem("weixinid")){
                if(sessionStorage.getItem("weixinlogin")){
                    return true;
                }else{
                    return false;
                }
            }else{
                return true;
            }
        }
    }
    return false;
}
function iswechat(){
    if(localStorage.getItem("safeExit")=="1"){//安全退出
        return false;
    }
    if(sessionStorage.getItem("weixinid")){
        return true;
    }
    return false;
}
function judgeJumpReloginUrl(_url){
    if(iswechat()==true){
        if(sessionStorage.getItem("notbind")){
            dialogConfirm('您还未开户或绑定账号，请先开户或绑定账号','开户/绑定','http://wap.southernfund.com/nfweixin/WeixinService/loginBind.xhtml?source=wechat','https://wap.southernfund.com/index.html');
        }else{
            wechatlogin("",1,"");
        }
    }else{
        if(_url){
              window.location.href=_url;
        }  
    }
}
function handletimeout(_url,callback,param,context){
    if(iswechat()){
        wechatlogin(callback,0,param,context);
    }else{        
        localStorage.setItem('timeout','true');
        if(_url){
            location.href = _url;
        }        
    }
}
function dialogConfirm(mcontent,confirmTitle,_url,_cancerUrl,confirmBtn,cancelBtn) {
    var   btnObj = {
        cancel:'取消'
    };
    if(cancelBtn){
        $.extend(btnObj,{
          cancel:cancelBtn
         })
    }
    if(confirmBtn){
        $.extend(btnObj,{
          confirm:confirmBtn
         })
    }
    
        dialog({
            type : 'confirm',
            hasTitle : false,
            content : mcontent,
            button :btnObj,
            cancelCallback : function(){
                if(_cancerUrl){
                    location.href = _cancerUrl
                }
            },
            confirmCallback : function() {
                if(typeof(_url) != 'function'){
                      location.href = _url
                }else{
                    _url&&_url();
                }
            }
        });        
}
function EncryptRC4(data){
    return data;    
}
//用于银行卡去除空格
function rem_bla(str){
    return str.replace(/\s/g,'');
}
function replaceByStar(str, leftLen, rightLen){
    if(str&&str.length>0){
        if(leftLen== undefined){ leftLen=0 }
        if(rightLen== undefined){ rightLen=0 }
        
        //长度不够leftLen，则全部返回星号
        if(str.length <= leftLen){
            return genFixNumStar(str.length);
        }
        
        // 长度不够leftLen+rightLen，则只保留前半部分的明文
        if(str.length <= leftLen + rightLen){
            return str.replace(new RegExp("(.{"+leftLen+"}).*"),"$1"+genFixNumStar(str.length - leftLen));
        }
               
        return str.replace(new RegExp("(.{"+leftLen+"}).*(.{"+rightLen+"})"),"$1"+genFixNumStar(str.length - leftLen - rightLen)+"$2");
    }else{
        return "";
    }
}

function genFixNumStar(len){
    var star = "";
    for(var i=0; i<len; i++){
        star += "*";
    } 
    return star;
}

//调用接口错误处理
function getAjaxError(type){
        //xhr, type['abort','timeout',parsererror,error], error
    if(type=='timeout'){
        $toast('请求超时，请检查网络状态','3500');
    }else if(type=='parsererror'){
        $toast('数据解析错误','3500');
    }else if(type=='abort'){
        $toast('请求丢失，请检查网络状态','3500');
    }else if(type=='error'||type==undefined){
        $toast('发现未知错误','3500');
    }
}

/*
    微信申购相关入口检测手势密码
*/
function checkLock(entry,param){
    if(!sessionStorage.getItem("debLock")&&localStorage.getItem('passwordxx')){//未解锁且设置过手势密码
        var H5LockParam =  {
            entry:entry,
            urlparam:param
        }
        localStorage.setItem('H5LockParam',json2str(H5LockParam));
        wechatlogin('',2,'H5lock.html');
 //       window.location.href = 'H5lock.html';
    }else{
        return true;//直接跳转下一页面
    }
}

function extendPostData(data){//扩展接口参数
    data = $.extend(data,{
        "devicetype" : getLocVal("deviceInfo.devicetype"),
        "clientversion" : getLocVal("deviceInfo.clientVersion"),
        //"platform" : getLocVal("app_platform"),
        "channel":"iapp"
    });
    if(islogin()) {
        data = $.extend(data,{
            "userid":Decrypt(sessionStorage.getItem("idno")),
            "accountId":sessionStorage.getItem("accountId"),
            "eqcustno":getLocVal("eqcustno"),
            "custno":getLocVal("custno"),
            "originalString":getLocVal("originalString"),
            "sessionkey":getLocVal("sessionkey")
        });
    }
    return data;
}

function  getPayType(capitalmode,interfacetype){
        switch(capitalmode){
            case "M":
            return "通联";break;
             case "3":
            return "银联通";break;
             case "5":
            return "好易联";break;
            case "E":
            return "支付宝";break;
            case "6":
            return "天天盈";break;
        }
        if(interfacetype == '1' || interfacetype == 1){
            return "快捷";
        }
        return '网银';
    }
    

//兼容负数
 Number.prototype.toFixed = function(s) {
            var that = this,changenum,index;
            // 负数
            if(this < 0){
                that = -that;
            }
            changenum = (parseInt(that * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();
            index = changenum.indexOf(".");
            if (index < 0 && s > 0) {
                changenum = changenum + ".";
                for (var i = 0; i < s; i++) {
                    changenum = changenum + "0";
                }
        
        
            } else {
                index = changenum.length - index;
                for (var i = 0; i < (s - index) + 1; i++) {
                    changenum = changenum + "0";
                }
        
        
            }
            if(this<0){
                return -changenum; 
            }else{
                return changenum; 
            }     
        }
  
//最小值
Array.prototype.min = function() {
var min = this[0];
var len = this.length;
for (var i = 1; i < len; i++){
if (parseFloat(this[i]) < parseFloat(min)){
min = this[i];
}
}
return min;
}
//最大值
Array.prototype.max = function() {
var max = this[0];
var len = this.length;
for (var i = 1; i < len; i++){
if (parseFloat(this[i]) > parseFloat(max)){
max = this[i];
}
}
return max;
}
function isnotBind(){
    if(sessionStorage.getItem("notbind")){
        return true;
    }
    return false;
}
function filterHtml(htmlcontent){
    try{
        var reg=/<[^<>]+>/g;
        htmlcontent=htmlcontent.replace(reg,'');        
    }catch(e){}
    return htmlcontent;
}
